# 封装对pymysql的相关调用
import logging
import os
import pymysql
from pymysql.cursors import DictCursor
from apiException.custom_exception import *
from utils.decoractors import singleton


@singleton
class Database:

    def __init__(self):
        # 因为只在内部去访问这个self.__db
        # 所以可以把它设置为私有属性
        self.__db = self.__get_connect()

    @staticmethod
    def __get_connect():
        # 创建连接对象的方法
        __data = eval(os.environ["DATABASE"])
        try:
            conn = pymysql.Connect(**__data,autocommit=True)
            return conn
        except Exception as e:
            logging.error(f"数据库连接失败，异常错误是{e}")
            raise DatabaseException()

    def get_one(self, sql):
        # 执行sql，需要1个返回值--查询
        try:
            with self.__db.cursor(pymysql.cursors.DictCursor) as cur:
                cur.execute(sql)
                return cur.fetchone()
        except Exception as e:
            logging.error(f"数据库查询失败，错误异常是{e}")
            raise GetDataException()

    def excute_sql(self,*sqls):  # *参数，表示不定传参，打包成一个元组
        # 执行sql，不需要返回值--删除、修改
        try:
            with self.__db.cursor(pymysql.cursors.DictCursor) as cur:
                for sql in sqls:
                    cur.execute(sql)

        except Exception as e:
            logging.error(f"数据库修改/删除失败，错误异常是{e}")
            raise ExecuteSqlException()

if __name__ == '__main__':
    db = Database()
    print(db)
    db2 = Database()
    print(db2)
    sql = "SELECT DISTINCT `year` FROM task_management"
    print(db.get_one(sql))

